package contracts

import (
	"encoding/json"
	"github.com/google/uuid"
	"github.com/hyperledger/fabric-contract-api-go/contractapi"
	"osa/contracts/model"
)

// 实例化对象
type UserContract struct {
	contractapi.Contract
}

// 链码初始化函数
func (u *UserContract) Init(ctx contractapi.TransactionContextInterface) error {
	//创建存储用户列表
	userList := new([]model.User)
	//将数据json化
	userListJson, err := json.Marshal(userList)
	if err != nil {
		return err
	}
	//将数据存储到账本中
	err = ctx.GetStub().PutState("users", userListJson)
	if err != nil {
		return err
	}
	return nil
}

// 判断用户是否已经注册
func (u *UserContract) IsRegister(ctx contractapi.TransactionContextInterface, email string) (bool, error) {
	//获取当前用户列表
	state, err := ctx.GetStub().GetState("users")
	if err != nil {
		return false, err
	}
	var userList []model.User
	//将数据进行unmarshal
	err = json.Unmarshal(state, &userList)
	if err != nil {
		return false, err
	}
	//遍历用户列表
	for _, user := range userList {
		if user.Email == email {
			return true, nil
		}
	}
	return false, nil
}

// 实现用户注册
func (u *UserContract) UserRegister(ctx contractapi.TransactionContextInterface, email string, pass string) error {
	//判断用户是否注册过
	isRegister, err := u.IsRegister(ctx, email)
	if err != nil || isRegister == true {
		return err
	}
	newUser := model.User{
		Id:     uuid.New().String(), //uuid
		Email:  email,
		Pass:   pass,
		Head:   "../assets/images/head.jpg", //注册设置默认头像
		Status: 1,
	}

	//获取当前用户列表
	state, err := ctx.GetStub().GetState("users")
	if err != nil {
		return err
	}
	var userList []model.User
	//将数据进行unmarshal
	err = json.Unmarshal(state, &userList)
	if err != nil {
		return err
	}

	//将新用户加入数组然后上传状态
	userList = append(userList, newUser)
	userListJson, err := json.Marshal(userList)
	if err != nil {
		return err
	}
	err = ctx.GetStub().PutState("users", userListJson)
	if err != nil {
		return err
	}
	return nil
}

// 实现用户登陆
func (u *UserContract) UserLogin(ctx contractapi.TransactionContextInterface, email string, pass string) (bool, error) {
	//获取当前用户列表
	state, err := ctx.GetStub().GetState("users")
	if err != nil {
		return false, err
	}
	var userList []model.User
	//将数据进行unmarshal
	err = json.Unmarshal(state, &userList)
	if err != nil {
		return false, err
	}
	//遍历用户列表
	for _, user := range userList {
		if user.Email == email && user.Pass == pass && user.Status == 1 {
			return true, nil
		}
	}
	return false, nil
}
